import {Component, EventEmitter, OnInit, Output, ViewChild} from '@angular/core';
import {AlertComponent, DynamicComponent, DynamicComponentEvent, LoadingComponent} from '../../../../../ng-tools';
import {HttpParams} from '@angular/common/http';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {TicketService} from '../../../../services/api/ticket.service';
import {timer} from 'rxjs';

@Component({
  selector: 'robot-produce',
  templateUrl: './robot-produce.component.html',
  styleUrls: ['./robot-produce.component.scss']
})
export class RobotProduceComponent implements OnInit, DynamicComponent {
  context: any;
  data: any;
  dynamic: true;
  events: DynamicComponentEvent;
  @Output() success = new EventEmitter();
  produceForm: FormGroup;
  nameFiles;
  avatarFiles;
  alterOption = {
    theme: 'success',
    data: '',
    position: 'center'
  };
  isLoading = false;
  @ViewChild('alert') private alert: AlertComponent;
  @ViewChild('nameInput') nameInput;
  @ViewChild('avatarInput') avatarInput;
  constructor(private formBuilder: FormBuilder,
              private ticketService: TicketService) {
    this.produceForm = this.formBuilder.group({
      generateCount: ['', Validators.required],
      nickNameExcel: ['', Validators.required],
      headImgZip: ['', Validators.required],
    });
  }

  ngOnInit() {
  }
  clickUploadName() {
    this.nameInput.nativeElement.click();
  }
  clickUploadAvatar() {
    this.avatarInput.nativeElement.click();
  }

  selectNameFile(e) {
      this.nameFiles = e.target.files[0];
  }
  selectAvatarFile(e) {
      this.avatarFiles = e.target.files[0];
  }

  produceRobot() {
    const formData = new FormData();
    formData.append('generateCount', this.produceForm.value.generateCount);
    formData.append('nickNameExcel', this.nameFiles);
    formData.append('headImgZip', this.avatarFiles);
    if (this.produceForm.valid) {
      // this.produceForm.reset();
      this.isLoading = true;
      this.alterOption.data = '正在上传文件并生产机器人';
      this.alterOption.theme = 'info';
      this.alert.show(this.alterOption);
      this.ticketService.post(this.ticketService.urls.generateRobots, formData, {
        observe: 'response',
        params: new HttpParams().append('web_token', localStorage.getItem('token'))}).subscribe((resp) => {
        if (resp.body.success) {
          this.alterOption.data = '机器人创建成功';
          this.alterOption.theme = 'success';
          this.alert.show(this.alterOption);
          this.isLoading = false;
          // this.success.emit();
        } else {
          this.alterOption.data = resp.body.msg + '请检查后重试';
          this.alterOption.theme = 'danger';
          this.alert.show(this.alterOption, 2000);
          this.isLoading = false;
        }
      }, (error) => {
        this.alterOption.data = '机器人生产失败,请检查后重试';
        this.alterOption.theme = 'danger';
        this.alert.show(this.alterOption, 2000);
        this.isLoading = false;
      });

    }
  }
}
